use std::path::Path;

use crate::{
    clipboard, img_utils, save_to_file, screenshot_from_remote,
    screenshot_local::{self, ScreenTarget},
    types::TResult,
};
use chrono::Local;
use image::{DynamicImage, ImageFormat};

pub struct SaveConfig {
    pub save_type_list: Option<Vec<String>>,
    pub save_path: Option<String>,
    pub auto_create_save_path: Option<bool>,
    pub img_save_type: Option<String>,
}

impl SaveConfig {
    pub fn get_img_save_type(&self) -> (&'static str, ImageFormat) {
        match &self.img_save_type {
            Some(img_save_type) => match img_save_type.as_str() {
                "png" => ("png", ImageFormat::Png),
                _ => ("jpg", ImageFormat::Jpeg),
            },
            None => ("jpg", ImageFormat::Jpeg),
        }
    }

    pub fn get_auto_create_save_path(&self) -> bool {
        match &self.auto_create_save_path {
            Some(item) => *item,
            None => false,
        }
    }
}

/// 截取远程截图到剪切板
pub async fn screen_from_remote(addr: String, save_config: &SaveConfig) -> TResult<()> {
    let img = screenshot_from_remote::screenshot(addr).await?;
    save(&img, save_config)
}

/// 截取本地屏幕到剪切板
pub async fn screen_from_local(screen: ScreenTarget, save_config: &SaveConfig) -> TResult<()> {
    let img = screenshot_local::screenshot_to_img(screen)?;
    save(&img, save_config)
}

fn save(img: &DynamicImage, save_config: &SaveConfig) -> TResult<()> {
    let mut save_result = vec![];
    match &save_config.save_type_list {
        Some(save_type_list) => save_type_list.iter().for_each(|item| match item.as_str() {
            "clipboard" => match clipboard::save_img_to_clipboard(img) {
                Ok(_) => (),
                Err(e) => {
                    save_result.push(e);
                }
            },
            "file" => match &save_config.save_path {
                Some(save_path) => {
                    let mut file_path = Path::new(&save_path).to_path_buf();
                    let now = Local::now();
                    let (suffix, format) = save_config.get_img_save_type();
                    let file_name =
                        format!("{}.{}", now.format("%Y%m%d%H%M%S").to_string(), suffix);
                    file_path.push(file_name);
                    match file_path.to_str() {
                        Some(file_path) => match img_utils::format_to_bytes(img, format) {
                            Ok(buf) => {
                                let res = save_to_file::save_bytes_to_file(
                                    file_path,
                                    &buf,
                                    save_config.get_auto_create_save_path(),
                                );
                                match res {
                                    Ok(_) => (),
                                    Err(e) => {
                                        save_result.push(e);
                                    }
                                }
                            }
                            Err(e) => {
                                save_result.push(e);
                            }
                        },
                        None => (),
                    }
                }
                None => (),
            },
            _ => (),
        }),
        None => (),
    }
    if save_result.len() <= 0 {
        Ok(())
    } else {
        Err("截图保存失败".into())
    }
}
